<template>
	<u-popup :show="open" @close="popupClose" @open="popupOpen" mode="bottom" :closeable="true"
		:closeOnClickOverlay="false" :customStyle="customStyle1" :round="20">
		<view class="wrapper" style="">
			<view class="blank20"></view>
			<view class="" v-if="addList.length>0">
				<text>已添加：</text>
				<template v-for="(v,i) in addList">
					<text>{{v.material_name}}{{v.qty}}{{v.unit_name}}{{i+1 == addList.length?'':'、'}}</text>
				</template>
			</view>
			<!-- <view class="blank20"></view> -->
			<!-- <u-gap height="40"></u-gap> -->
			<view class="blank20"></view>
			<view class="text-gray tips-box">请说出你要采购的食材和数量，如：“土豆30斤”</view>
			<view class="blank20"></view>
			<!-- <u--textarea v-model="textareaValue" disabled placeholder="请说出你要采购的食材和数量，如：“土豆30斤”"></u--textarea> -->
			<view class="flex">
				<view class="">
					<u--input placeholder="食材" border="surround" v-model="name" @blur="search" :customStyle="nameError?inputErrorCustomStyle:inputCustomStyle"></u--input>
				</view>
				<view class="ml10">
					<u--input placeholder="数量" border="surround" type="number" v-model="num" @blur="search"  :customStyle="numError?inputErrorCustomStyle:inputCustomStyle"></u--input>
				</view>
				<view class="ml10">
					<u--input placeholder="单位" border="surround" v-model="unit" @blur="search" :customStyle="unitError?inputErrorCustomStyle:inputCustomStyle"></u--input>
				</view>
				<!-- <view class="ml10 text-center text-primary" style="width: 80px;">
					添加
				</view> -->
			</view>
			<template v-if="errorTips || tips">
				<view class="blank20"></view>
				<view v-if="errorTips" class="text-red">{{errorTips}}</view>
				<view v-if="tips">{{tips}}</view>
			</template>
			<view class="blank20"></view>
			<view class="flex">
				<view class="flex-1">
					<u-button text="添加" shape="circle" :plain="true" type="primary" size="small" :disabled="!isAdd"  @click="add"></u-button>
				</view>
				<view class="ml10 mr10"></view>
				<view class="flex-1">
					<u-button text="添加后关闭" shape="circle" :plain="true" type="primary" size="small" @click="addAndClose" :disabled="!isAdd"></u-button>
				</view>
			</view>
			<view class="blank20"></view>
			<template v-if="longPress == '2'">
				<view>
					<text class="text-red">松手停止</text>
					<text>，{{'剩余：' + count + 's'}}</text>
				</view>
				<view class="blank20"></view>
			</template>
			<view class="btn-recorder" @longpress="longpressBtn" @touchend="touchendBtn">
				{{longPress == '1' ? '按住说话' : '说话中...'}}
			</view>
			<!-- <view class="btn-recorder" @click="upload">
				电脑上测试上传音频
			</view> -->
			<!-- <u-button :text="btnText" shape="circle" :loading="btnLoading" type="success" @longpress="longpress"></u-button> -->
			<view class="blank20"></view>
		</view>

	</u-popup>
</template>

<script>
	import {
		upload
	} from '@/common/api.js';
	
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	let init; // 录制时长计时器
	let timer; // 播放 录制倒计时

	export default {
		name: "recorder-popup",
		props: {
			open: Boolean,
			data:Array,
			page: String,
		},
		data() {
			return {
				btnText: '按住 说话',
				btnLoading: false,
				textareaValue: '',
				customStyle1: {
					// 'background':'none'
				},
				count: null, // 录制倒计时
				longPress: '1', // 1显示 按住说话 2显示 说话中
				delShow: false, // 删除提示框显示隐藏
				time: 0, //录音时长
				duration: 60000, //录音最大值ms 60000/1分钟
				tempFilePath: '', //音频路径
				playStatus: 0, //录音播放状态 0:未播放 1:正在播放
				name:'',
				num:'',
				unit:'',
				tips:'',
				errorTips:'',
				resultData:null,
				nameError:false,
				unitError:false,
				numError:false,
				inputErrorCustomStyle:{
					'border-color': '#ff0000 !important'
				},
				inputCustomStyle:{},
				addList:[]
			};
		},
		watch:{
			open(newVal, oldVal) {
				this.resultData = null;
				this.name = '';
				this.num = '';
				this.unit = '';
				this.tips = '';
				this.errorTips = '';
				this.addList = [];
				this.nameError = false;
				this.numError = false;
				this.unitError = false;
			}
		},
		computed:{
			isAdd(){
				let flag = false;
				if(this.name && this.num && this.unit){
					if(this.errorTips){
						flag = false;
					}else if(!this.resultData){
						flag = false;
					}else{
						flag = true;
					}
				}
				return flag;
			}
		},
		methods: {
			onNameBlur(){
				this.search();
			},
			add(){
				// if(!this.resultData){
				// 	uni.$u.toast('请先输入');
				// 	return;
				// }
				// if(this.errorTips){
				// 	uni.$u.toast('添加失败');
				// 	return;
				// }
				let _this = this;
				this.$emit("add",this.resultData);
				let item = JSON.parse(JSON.stringify(this.resultData));
				this.addList.push(item)
			},
			addAndClose(){
				this.add();
				this.popupClose();
			},
			upload(){
				let _this = this;
				// upload('/static/images/login.jpg').then((res) => {
				// })
				// let tempFilePath = '/static/test_voice_sc_mp3_16_mono.mp3';
				let tempFilePath = this.tempFilePath;
				uni.showLoading({
					title: '加载中'
				});
				console.log(tempFilePath);
				uni.uploadFile({
					// https://fmn315.xyz/gmm/upload
					url: 'https://ai.fmn315.cn/upload/',
					filePath: tempFilePath,
					name: 'file',
					formData: {},
					success: (uploadFileRes) => {
						// console.log(result);
						// console.log(result['食材名称']);
						try{
							let result = JSON.parse(JSON.parse(uploadFileRes.data));
							// {食材名称: "土豆", 数量: 3, 单位: "斤"}
							_this.name = result['食材名称'];
							_this.num = result['数量'];
							_this.unit = result['单位'];
							
							uni.hideLoading();
						}catch(e){
							//TODO handle the exception
							uni.$u.toast('翻译失败');
						}
						this.search();
					},
					fail:(res)=>{
						uni.$u.toast('上传失败');
					},
					complete:()=>{
						
					}
				});
			},
			search(){
				this.errorTips = "食材搜索中，请稍等...";
				this.tips = '';
				this.nameError = false;
				this.unitError = false;
				this.numError = false;
				
				let material_item = this.data;
				// console.log(material_item);
				let material = material_item.find(v=>{
					// let name = v.name.split('-')[0];
					return v.mname == this.name;	
				});
				if(!material){
					this.errorTips = '没有该食材，请重新语音录入，或编辑修正。'
					this.tips = '';
					this.nameError = true;
					return;
				}
				if(!this.num){
					this.errorTips = '没有数量，请重新语音录入，或编辑修正。'
					this.tips = '';
					this.numError = true;
					return;
				}
				let material_purchase_unit_category = this.$store.getters.get_material_purchase_unit_category;
				// let material_purchase_unit_category_obj = this.toObj(material_purchase_unit_category,'id');
				let result_unit = material_purchase_unit_category.find(v=>v.name == this.unit);
				if(!result_unit){
					this.errorTips = '没有该单位，请重新语音录入，或编辑修正。'
					this.tips = '';
					this.unitError = true;
					return;
				}
				let use_unit_id;
				let material_id;
				let main_unit_id;
				let purchase_unit_id;
				if(Array.isArray(material.main_unit_id)){
					main_unit_id = material.main_unit_id;
				}else{
					let _unit = material_purchase_unit_category.find(v=>v.id == material.main_unit_id);
					main_unit_id = [_unit.id,_unit.name];
				}
				if(Array.isArray(material.purchase_unit_id)){
					purchase_unit_id = material.purchase_unit_id;
				}else{
					let _unit = material_purchase_unit_category.find(v=>v.id == material.purchase_unit_id);
					purchase_unit_id = [_unit.id,_unit.name];
				}
				
				if(this.page == 'stockOutFood'){
					use_unit_id = main_unit_id;
					material_id = material.material_id[0];
				}else{
					use_unit_id = purchase_unit_id;
					material_id = material.id;
				}
				if(result_unit.id != use_unit_id[0]){
					this.errorTips = '';
					let _text = '采购单位';
					if(this.page == 'stockOutFood'){
						_text = '主单位';
					}
					this.tips = `“${this.unit}”不是${this.name}的${_text}，添加时将自动更改为“${use_unit_id[1]}”`;
				}else{
					this.errorTips = ''
					this.tips = '搜索成功，可添加。';
				}
				this.resultData = {
					material_id:material_id,
					material_name:this.name,
					unit_id:use_unit_id[0],
					unit_name:use_unit_id[1],
					qty:Number(this.num),
				};
			},
			popupClose() {
				// this.open = false;
				this.$emit("close");
			},
			popupOpen() {

			},
			longpressBtn() {
				console.log('longpress');
			},
			touchendBtn() {

			},
			// 倒计时
			countdown(val) {
				let _then = this;
				if(!val){
					clearInterval(timer);
				}
				_then.count = Number(val);
				timer = setInterval(function() {
					if (_then.count > 0) {
						_then.count--
					} else {
						_then.longPress = '1';
						clearInterval(timer);
					}
				}, 1000);
			},
			// 长按录音事件
			longpressBtn() {
				this.longPress = '2';
				this.countdown(60); // 倒计时
				clearInterval(init) // 清除定时器
				// return;
				recorderManager.onStop((res) => {
					this.tempFilePath = res.tempFilePath;
					this.recordingTimer(this.time);
					this.countdown(); // 清除倒计时
				})
				const options = {
					duration: this.duration, // 指定录音的时长，单位 ms
					sampleRate: 16000, // 采样率
					numberOfChannels: 1, // 录音通道数
					encodeBitRate: 96000, // 编码码率
					format: 'mp3', // 音频格式，有效值 aac/mp3
					frameSize: 10, // 指定帧大小，单位 KB
				}
				this.recordingTimer();
				recorderManager.start(options);
				// 监听音频开始事件
				recorderManager.onStart((res) => {
					console.log(res)
				})
			},
			// 长按松开录音事件
			touchendBtn() {
				this.longPress = '1';
				// return;
				recorderManager.onStop((res) => {
					console.log(res);
					this.tempFilePath = res.tempFilePath;
					this.upload();
				})
				this.recordingTimer(this.time);
				this.countdown(); // 清除倒计时
				recorderManager.stop()
			},
			recordingTimer(time) {
				let that = this;
				if (time == undefined) {
					// 将计时器赋值给init
					init = setInterval(function() {
						that.time++
					}, 1000);
				} else {
					clearInterval(init)
				}
			},
			// 删除录音
			delBtn() {
				this.delShow = false;
				this.time = 0
				this.tempFilePath = ''
				this.playStatus = 0
				innerAudioContext.stop()
			},
			// 播放
			playBtn() {
				innerAudioContext.src = this.tempFilePath
				//在ios下静音时播放没有声音，默认为true，改为false就好了。
				// innerAudioContext.obeyMuteSwitch = false
				//点击播放
				if (this.playStatus == 0) {
					this.playStatus = 1;
					innerAudioContext.play();
					this.countdown(this.time); // 倒计时
				} else {
					this.playStatus = 0;
					innerAudioContext.pause()
				}
				// //播放结束
				innerAudioContext.onEnded(() => {
					this.playStatus = 0;
					innerAudioContext.stop();
				})
			},
		}
	}
</script>

<style>
	.btn-recorder {
		border-radius: 70upx;
		line-height: 70upx;
		color: #fff;
		background-color: #5ac725;
		border-color: #5ac725;
		border-width: 1px;
		border-style: solid;
		text-align: center;
	}
</style>